import { Http, Headers, Response,Jsonp, RequestOptions, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/toPromise';

import { Injectable } from '@angular/core';

import { Order } from './order';
import { SERVER} from '../../app.config';

@Injectable()
export class OrderService {

    constructor(private http: Http){

    }

    getOrders(): Promise<Order[]> {
        return this.http.get(SERVER.ORDER + "/date")
        .toPromise()
        .then(response => response.json().order_list as Order[])
        .catch(this.handleError);
    }

    getOrdersBypsid(passenger_id: string): Promise<Order[]> {
        if(typeof(passenger_id) == "undefined"){
            passenger_id = '';
        }
        return this.http.get(SERVER.ORDER + "/findpsid"+"?passenger_id="+passenger_id)
        .toPromise()
        .then(response => response.json().order_list as Order[])
        .catch(this.handleError);
    }

    

    searchOrders(start_time: string, end_time: string): Promise<Order[]> {
        let url = SERVER.ORDER + "/date?start_time=" + start_time + '&end_time=' + end_time;
        return this.http.get(url)
        .toPromise()
        .then(response => response.json().order_list as Order[])
        .catch(this.handleError);
    }

    getOrder(order_id: number) {
        return this.getOrders()
            .then(orders => orders.find(order => order.order_id ===order_id ));
    }

    private handleError(error: any): Promise<any> {
        console.error('错误：', error);

        return Promise.reject(error.message || error);
    }

    //添加
    private post(order: Order): Promise<Order> {
        let headers = new Headers({
            'Content-type': 'application/json'});

        return this.http.post(SERVER.ORDER, JSON.stringify(order), {headers: headers})
        .toPromise()
        .then(res => res.json().data)
        .catch(this.handleError);
    }

    //更新
    private put(order: Order): Promise<Order> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let url = `${SERVER.ORDER}`;

        return this.http.put(url, JSON.stringify(order), {headers: headers})
                   .toPromise()
                   .then(() => order)
                   .catch(this.handleError);
    }

    //删除
    delete(order: Order): Promise<Response> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let url = `${SERVER.ORDER}/${order.order_id}`;

        return this.http
                   .delete(url, { headers: headers})
                   .toPromise()
                   .catch(this.handleError);
    }

    //保存
    save(order: Order): Promise<Order> {
        if (order.order_id) {
            return this.put(order)
        }
        return this.post(order);
    }
}